import logging

from flask import render_template, session, jsonify, request, g
from flask import current_app

from info import constants
from info.models import User, Category, News
from info.modules.index import index_blue
from info.utils.common import login_user
from info.utils.response_code import RET


@index_blue.route("/")
@login_user
def index():
    """
    从session 中检查用户的登录状态
    :return: 用户信息
    """

    # 定义列表保存分类数据
    categories_dicts = []
    click_news_list = []
    # 获取用户id
    user = g.user
    # 查询分类信息
    try:
        # 获取新闻分类数据
        categories = Category.query.all()
        for category in categories:
            # 拼接内容
            categories_dicts.append(category.to_dict())
    except Exception as e:
        logging.error("查询分类信息失败", e)
    # 点击排行信息
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.ADMIN_NEWS_PAGE_MAX_COUNT)
        if news_list:
            for news in news_list:
                click_news_list.append(news.to_basic_dict())
    except Exception as e:
        logging.error("查询排行信息失败", e)

    data = {
        "user_info": user.to_dict() if user else None,
        "categories": categories_dicts,
        "click_news_list": click_news_list
    }
    return render_template("news/index.html", data=data)


@index_blue.route("/favicon.ico")
# 浏览器图标
def favicon():
    # 需要返回静态资源 send_static_file
    return current_app.send_static_file("news/gan.png")


@index_blue.route('/news_list')
def get_news_list():
    """
    获取指定分类的新闻列表
    1. 获取参数
    2. 校验参数
    3. 查询数据
    4. 返回数据
    :return:
    """

    # 1. 获取参数
    args_dict = request.args
    page = args_dict.get("p", '1')
    per_page = args_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)
    category_id = args_dict.get("cid", '1')

    # 2. 校验参数
    try:
        category_id = int(category_id)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 查询数据并分页
    filters = []
    filters.append(News.status != 1)
    # 如果分类id不为1，那么添加分类id的过滤
    if category_id != 1:
        filters.append(News.category_id == category_id)
    try:
        # *filter 展开查询条件
        paginates = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

        # 获取查询出来的数据
        items = paginates.items
        # 获取到总页数
        total_page = paginates.pages
        current_page = paginates.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_list = []
    for news in items if items else []:
        news_list.append(news.to_basic_dict())

    # 4. 返回数据
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_list,
        "cid": category_id

    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
